import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { GetMenuApi } from '@/request/user/login-api'

// 解决 vue-router 升级导致的 Uncaught(in promise)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return originalReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'mainlayout',
    component: () => import('../views/layout/MainLayout.vue'),
    redirect: '/home',
    children: []
  }, {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }, {
    path: '/NotFound',
    name: 'not-found',
    component: () => import('../views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  const accessToken = localStorage.getItem('accessToken')
  const refreshToken = localStorage.getItem('refreshToken')
  //用户访问登陆页面但是token已经存在(freshToken和accessToken存在其一)，跳转到首页
  if (to.path === '/login' && (accessToken || refreshToken)) {
    next('/')
    return
  }
  //用户访问非登录页面，但是没有token，跳转到登录界面
  if (to.path !== '/login' && !(accessToken || refreshToken)) {
    next('/login')
    return
  }
  // 获取用户能够访问的菜单信息
  if ((accessToken || refreshToken) && store.state.userMenuData.menuData.length === 0) {
    let res = await GetMenuApi()
    //考虑accessToken过期但是refreshToken未过期的情况,重新请求
    if (res.code !== 200) {
      res = await GetMenuApi()
      console.log('重新请求菜单')
    }
    if (res.code === 200) {
      store.commit('userMenuData/changeMenuData', res.data)
      //生成菜单路由
      //初始数据
      let newMenuChildrenRoutes = [{
        path:"/profile",
        meta: {titles: ["修改密码"]},
        component:()=>import("@/views/profile/Profile.vue")
      }]
      res.data.forEach(item => {
        //有父目录
        if (item.childItem) {
          let ret = item.childItem.map(sitem => {
            let dir = item.name
            return {
              path: sitem.path,
              meta: { titles: [item.title, sitem.title] },
              component: () => import(`../views/${dir}/${sitem.name}.vue`)
            }
          })
          newMenuChildrenRoutes = [...newMenuChildrenRoutes, ...ret]
        }
        //无父目录
        else if (item.childItem === null && item.name !== null) {
          let dir = item.name.toLowerCase()
          let rea = {
            path: item.path,
            meta: { titles: [item.title] },
            component: () => import(`../views/${dir}/${item.name}.vue`)
          }
          newMenuChildrenRoutes.push(rea)
        }
      })
      //添加到mainlayout路由的children中去
      newMenuChildrenRoutes.forEach(item => {
        router.addRoute('mainlayout', item)
      })
      //如果直接next,路由还是为空
      next(to.path)
      return
    }
  }
  if (to.matched.length === 0) {
    next('/NotFound')
  }
  //放行
  next()
})
export default router
